
import { showToast } from 'vant'
import { ref, onMounted } from 'vue'
export default function (audio, progress, currentMusic, skip, scrollLyr, modeMap, modeIndex, currentIndex, musicList, randomMusicIndex, randomMusicList) {

    let progressWidth = 0
    let isPlaying = ref(false) //  默认不播放

    function canplay() {
        currentMusic.value.duration = audio.value.duration
        audio.value.play()
    }
    // 事件更新
    function timeupdate() {
        currentMusic.value.currentTime = audio.value.currentTime
        let t = audio.value.currentTime * 1000
        skip(t)
        scrollLyr()
    }

    //  跳转
    function changeTime(e) {

        let x = e.offsetX - 0

        audio.value.currentTime = (x / progressWidth) * currentMusic.value.duration
    }

    //  播放完毕事件
    function ended() {

        let mode = modeMap[modeIndex.value]
        if (mode.name === '顺序播放') {
            //  切换到下一首
            currentIndex.value++
            if (currentIndex.value >= musicList.value.length) {
                showToast('播放完毕')
                return
            }
            currentMusic.value = musicList.value[currentIndex.value]
        } else if (mode.name === '单曲循环') {
            //
            // console.dir(audio.value)
            // loop.value = true
        } else if (mode.name === '随机播放') {
            randomMusicIndex.value++
            if (randomMusicIndex.value >= randomMusicList.value.length) {
                randomMusicIndex.value = 0
                randomMusicList.value = [...musicList.value].sort(() => {
                    return Math.random() - 0.5
                })
            }
            currentMusic.value = randomMusicList.value[randomMusicIndex.value]
        } else if (mode.name === '列表循环') {
            currentIndex.value++
            if (currentIndex.value >= musicList.value.length) {
                currentIndex.value = 0
            }
            currentMusic.value = musicList.value[currentIndex.value]
        }
    }

    function prev() { }

    function togglePlay() {
        if (isPlaying.value) {
            audio.value.pause()
        } else {
            audio.value.play()
        }

        isPlaying.value = !isPlaying.value
    }

    function play() {
        // console.dir(e.target.paused)
        isPlaying.value = true
    }
    function pause() {
        // console.dir(e.target.paused)
        isPlaying.value = false
    }

    onMounted(() => {
        progressWidth = progress.value.offsetWidth - 0
    })


    return {
        canplay,
        timeupdate,
        changeTime,
        ended,
        togglePlay,
        play,
        pause,
        prev,
        isPlaying
    }
}